package com.qcby.aop_cftj.aspect;
import com.qcby.aop_cftj.myannotation.NoRepeatSubmit;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Component
@Aspect
public class NoRepeatSubmitAspect {
    @Autowired
    private  RedisTemplate<String,Object> redisTemplate;
    @Pointcut("@annotation(repeatSubmit)")
    public void pointcutNoRepeat(NoRepeatSubmit repeatSubmit){};
    @Around("pointcutNoRepeat(noRepeatSubmit)")
    public  Object doNoRepeat(ProceedingJoinPoint point, NoRepeatSubmit noRepeatSubmit) throws Throwable {
        int i=noRepeatSubmit.lockTime();
        HttpServletRequest httpServletRequest = HttpServletRequest();
        Cookie[] cookies = httpServletRequest.getCookies();
        String token="";
        if(cookies!=null){
            for (Cookie cookie : cookies) {
               if(cookie.getName().equals("token")){
                   token=cookie.getValue().toString();
               }
            }
        }
        String url = httpServletRequest.getRequestURL().toString();
        String sign = url+"/"+token;
        Boolean key=redisTemplate.hasKey(sign);
        if (key){
            System.out.println("请勿重复提交！！");
            return null;
//            throw new Exception("请勿重复提交");

        }
        redisTemplate.opsForValue().set(sign,sign,i, TimeUnit.SECONDS);
        return  point.proceed();
    }
    public static HttpServletRequest HttpServletRequest(){
        return ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
    }

}
